package org.intellij.doctree.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import org.intellij.doctree.ApplicationDocs;
import org.intellij.doctree.DocTree;
import org.intellij.doctree.DocTreeComponent;
import org.intellij.doctree.ProjectDocs;

import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;

public abstract class TreeEditAction extends AnAction {

    public DocTreeComponent getComponent(AnActionEvent e) {
        String place = e.getPlace();
        DocTreeComponent component = null;
        if (ApplicationDocs.ACTION_PLACE.equals(place)) {
            Application application = ApplicationManager.getApplication();
            if (application != null)
                component = (DocTreeComponent) application.getComponent(ApplicationDocs.COMPONENT_NAME);
        } else if (ProjectDocs.ACTION_PLACE.equals(place)) {
            Project project = (Project) e.getDataContext().getData(DataConstants.PROJECT);
            if (project != null)
                component = (DocTreeComponent) project.getComponent(ProjectDocs.COMPONENT_NAME);
        }
        return component;

    }

    public DocTree getTree(AnActionEvent e) {
        Project project = (Project) e.getDataContext().getData(DataConstants.PROJECT);
        if (project == null) return null;

        DocTree tree = null;
        String place = e.getPlace();
        ProjectDocs projDocs = (ProjectDocs) project.getComponent(ProjectDocs.COMPONENT_NAME);
        if (ApplicationDocs.ACTION_PLACE.equals(place)) {
            tree = projDocs.getApplicationTree();
        } else if (ProjectDocs.ACTION_PLACE.equals(place)) {
            tree = projDocs.getProjectTree();
        }
        return tree;
    }

    public JComponent getSource(AnActionEvent e) {
        return (JComponent) e.getInputEvent().getSource();
    }

    protected Point getLocation(AnActionEvent e) {
        if (e != null) {
            InputEvent inputEvent = e.getInputEvent();
            if (inputEvent instanceof MouseEvent)
                return ((MouseEvent) inputEvent).getPoint();
        }
        return null;
    }

}
